<template>
  <div class="app-container">
    <el-form :inline="true" :model="listQuery" size="small" label-width="100">
      <el-form-item label="商品名称：">
        <el-input v-model="listQuery.productName" class="input-width" placeholder="商品名称"></el-input>
      </el-form-item>
      <el-form-item label="推荐状态：">
        <el-select v-model="listQuery.recommendStatus" placeholder="全部" clearable class="input-width">
          <el-option v-for="item in RECOMMEND_STATUS_MAP" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearchList" size="small"> 搜索 </el-button>
        <el-button @click="handleResetSearch" size="small"> 重置 </el-button>
        <el-button size="small" class="btn-add" @click="handleSelectProduct">选择商品</el-button>
      </el-form-item>
    </el-form>
    <div class="table-container">
      <el-table
        ref="newProductTable"
        height="100%"
        :data="list"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="listLoading"
        border
      >
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <el-table-column label="编号" width="80" align="center">
          <template #default="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="商品名称" min-width="250" show-overflow-tooltip align="center">
          <template #default="scope">{{ scope.row.productName }}</template>
        </el-table-column>
        <el-table-column label="是否推荐" width="100" align="center">
          <template #default="scope">
            <el-switch
              @change="handleRecommendStatusStatusChange(scope.$index, scope.row)"
              :active-value="1"
              :inactive-value="0"
              v-model="scope.row.recommendStatus"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="排序" width="80" align="center">
          <template #default="scope">{{ scope.row.sort }}</template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            {{ formatRecommendStatus(scope.row.recommendStatus) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button size="small" type="primary" link @click="handleEditSort(scope.row)"> 排序 </el-button>
            <el-button size="small" type="danger" link @click="handleDelete(scope.row)">删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="batch-operate-container">
      <el-select size="small" v-model="operateType" placeholder="批量操作">
        <el-option v-for="item in OPERATE_STATUS_MAP" :key="item.value" :label="item.label" :value="item.value"> </el-option>
      </el-select>
      <el-button class="search-button" @click="handleBatchOperate()" type="primary" size="small"> 确定 </el-button>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="listQuery.pageSize"
        :page-sizes="[5, 10, 15]"
        v-model:current-page="listQuery.pageNum"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog title="选择商品" v-model="selectDialogVisible" width="50%">
      <el-input v-model="selectListQuery.keyword" style="width: 250px; margin-bottom: 20px" size="small" placeholder="商品名称搜索">
        <template #append>
          <el-button :icon="Search" @click="handleSelectSearch"></el-button>
        </template>
      </el-input>
      <el-table :data="selectList" height="100%" @selection-change="handleDialogSelectionChange" border>
        <el-table-column type="selection" width="60" align="center" fixed></el-table-column>
        <el-table-column label="商品名称" min-width="250" show-overflow-tooltip align="center">
          <template #default="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column label="货号" width="160" align="center">
          <template #default="scope">NO.{{ scope.row.productSn }}</template>
        </el-table-column>
        <el-table-column label="价格" width="120" align="center">
          <template #default="scope">￥{{ scope.row.price }}</template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleDialogSizeChange"
          @current-change="handleDialogCurrentChange"
          layout="prev, pager, next"
          v-model:current-page="selectListQuery.pageNum"
          :page-size="selectListQuery.pageSize"
          :page-sizes="[5, 10, 15]"
          :total="selectTotal"
        >
        </el-pagination>
      </div>
      <div style="clear: both"></div>
      <template #footer>
        <el-button size="small" @click="selectDialogVisible = false"> 取 消 </el-button>
        <el-button size="small" type="primary" @click="handleSelectDialogConfirm"> 确 定 </el-button>
      </template>
    </el-dialog>
    <el-dialog title="排序" v-model="sortDialogVisible" width="400px">
      <el-form :model="sortDialogData" label-width="80">
        <el-form-item label="排序：">
          <el-input v-model="sortDialogData.sort"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="small" @click="sortDialogVisible = false"> 取 消 </el-button>
        <el-button size="small" type="primary" @click="handleUpdateSort"> 确 定 </el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { fetchList, updateRecommendStatus, deleteHotProduct, createHotProduct, updateHotProductSort } from '@/api/hotProduct'
import { fetchList as fetchProductList } from '@/api/product'
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { OPERATE_STATUS_MAP, RECOMMEND_STATUS_MAP } from '@/constant'
import type { Hot, HotPageDto } from '@/models/hot'
import { Search } from '@element-plus/icons-vue'
import type { HotPorductParams, HotPorductUpdateSortParams } from '@/models/hotProduct'
import type { Product, ProductPageParams } from '@/models/product'

defineOptions({ name: 'HotProductList' })

const listQuery = ref<HotPageDto>({ pageNum: 1, pageSize: 10 })
const list = ref<Hot[]>([])
const total = ref(0)
const listLoading = ref(false)
const multipleSelection = ref<Hot[]>([])
const operateType = ref(null)
const selectDialogVisible = ref(false)
const sortDialogVisible = ref(false)
const sortDialogData = ref<HotPorductUpdateSortParams>({ id: '' })

const selectListQuery = ref<ProductPageParams>({ pageNum: 1, pageSize: 10 })
const selectTotal = ref(0)
const selectList = ref<Product[]>([])
const selectMultipleSelection = ref<Hot[]>([])
getList()

function formatRecommendStatus(status: number) {
  if (status === 1) {
    return '推荐中'
  } else {
    return '未推荐'
  }
}

function handleResetSearch() {
  listQuery.value = { pageNum: 1, pageSize: 10 }
}

function handleSearchList() {
  listQuery.value.pageNum = 1
  getList()
}

function handleSelectionChange(val: Hot[]) {
  multipleSelection.value = val
}

function handleSizeChange(val: number) {
  listQuery.value.pageNum = 1
  listQuery.value.pageSize = val
  getList()
}

function handleCurrentChange(val: number) {
  listQuery.value.pageNum = val
  getList()
}

function handleRecommendStatusStatusChange(index: number, row: Hot) {
  updateRecommendStatusStatus(row.id + '', row.recommendStatus as number)
}

function handleDelete(row: Hot) {
  deleteProduct(row.id + '')
}

function handleBatchOperate() {
  if (multipleSelection.value.length < 1) {
    ElMessage.warning('请选择一条记录')
    return
  }
  const ids = multipleSelection.value.map((row: Hot) => row.id as number).join(',')
  if (operateType.value === 0) {
    //设为推荐
    updateRecommendStatusStatus(ids, 1)
  } else if (operateType.value === 1) {
    //取消推荐
    updateRecommendStatusStatus(ids, 0)
  } else if (operateType.value === 2) {
    //删除
    deleteProduct(ids)
  } else {
    ElMessage.warning('请选择批量操作类型')
  }
}

function handleSelectProduct() {
  selectDialogVisible.value = true
  getDialogList()
}

function handleSelectSearch() {
  getDialogList()
}

function handleDialogSizeChange(val: number) {
  selectListQuery.value.pageNum = 1
  selectListQuery.value.pageSize = val
  getDialogList()
}

function handleDialogCurrentChange(val: number) {
  selectListQuery.value.pageNum = val
  getDialogList()
}

function handleDialogSelectionChange(val: any) {
  selectMultipleSelection.value = val
}

async function handleSelectDialogConfirm() {
  if (selectMultipleSelection.value.length < 1) {
    ElMessage.warning('请选择一条记录')
    return
  }
  const selectProducts: HotPorductParams[] = selectMultipleSelection.value.map((row: any) => ({
    productId: row.id,
    productName: row.name,
  }))
  await ElMessageBox.confirm('使用要进行添加操作?', '提示', { type: 'warning' })
  await createHotProduct(selectProducts)
  selectDialogVisible.value = false
  selectMultipleSelection.value = []
  getList()
  ElMessage.success('添加成功')
}

function handleEditSort(row: Hot) {
  sortDialogVisible.value = true
  sortDialogData.value.sort = row.sort
  sortDialogData.value.id = row.id + ''
}

async function handleUpdateSort() {
  await ElMessageBox.confirm('是否要修改排序?', '提示', { type: 'warning' })
  await updateHotProductSort(sortDialogData.value)
  sortDialogVisible.value = false
  getList()
  ElMessage('删除成功')
}

async function getList() {
  listLoading.value = true
  try {
    const res = await fetchList(listQuery.value)
    list.value = res.data.data.list
    total.value = res.data.data.total
  } finally {
    listLoading.value = false
  }
}

async function updateRecommendStatusStatus(ids: string, status: number) {
  try {
    await ElMessageBox.confirm('是否要修改推荐状态?', '提示', { type: 'warning' })
    let params = { ids, recommendStatus: status }
    await updateRecommendStatus(params)
    getList()
    ElMessage.success('修改成功')
  } catch {
    getList()
  }
}

async function deleteProduct(ids: string) {
  await ElMessageBox.confirm('是否要删除该推荐?', '提示', { type: 'warning' })
  await deleteHotProduct({ ids })
  getList()
  ElMessage.success('删除成功')
}

async function getDialogList() {
  const response = await fetchProductList(selectListQuery.value)
  selectList.value = response.data.data.list
  selectTotal.value = response.data.data.total
}
</script>
<style></style>
